//
//  ViewController.m
//  解档归档存储数据
//
//  Created by 伍银荣 on 2021/6/28.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ViewController.h"
#import "Teacher.h"

@interface ViewController ()



@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, copy) NSString *filePath2;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

//存数据
- (IBAction)saveBtnClicked:(id)sender {
    
    NSLog(@"home = %@",NSHomeDirectory());
    //第一种方法:使用NSKeyedArchiver的类方法创建出了NSData类型的数据data,接着将data吸入相应的文件中.
    _filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"teacher.data"];
    Teacher *t1 = [[Teacher alloc]init];
    t1.name = @"RoseLily";
    t1.age = 24;
    NSError *error = nil;
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:t1 requiringSecureCoding:YES error:&error];
    if (error) {
        NSLog(@"归档失败,失败的原因是:%@",error);
    }
   BOOL success = [data writeToFile:_filePath atomically:YES];
    if (success) {
        NSLog(@"写入成功");
    } else {
        NSLog(@"写入失败");
    }
    
    
    
    //第二种方法:使用NSKeyedArchiver的实例化方法创建出archiver对象,归档相应对象的键值,再将归档后的数据写入文件中
    Teacher *t = [[Teacher alloc]init];
    t.name = @"Jack";
    t.age = 12;
    _filePath2 = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"teacer2.data"];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initRequiringSecureCoding:YES];
    [archiver encodeObject:t forKey:@"Teacher"];
    [archiver encodedData];
    [archiver.encodedData writeToFile:_filePath2 atomically:YES];
    
    
    
    
}


//取数据
- (IBAction)readBtnClicked:(id)sender {
  //  解档:获取到文件路径中的内容data,然后解档Teacher类的data数据
    NSData *data = [NSData dataWithContentsOfFile:_filePath];
    NSError *error = nil;
    Teacher *t = [NSKeyedUnarchiver unarchivedObjectOfClass:[Teacher class] fromData:data error:&error];
    if (error) {
        NSLog(@"解档失败");
    } else {
        NSLog(@"解档成功--name = %@,age = %d",t.name, t.age);
    }
    
    
    
    //第二种方法:实例化NSKeyedUnarchiver
    NSError *error2 = nil;
    NSData *data2 = [NSData dataWithContentsOfFile:_filePath2];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingFromData:data2 error:&error2];
    //这里必须要是decodeObjectOfClass这个方法,指定解档的是哪个类,不能直接写decodeObjectForkey这个方法
    Teacher *t2= [unarchiver decodeObjectOfClass:[Teacher class] forKey:@"Teacher"];
    if (error) {
        NSLog(@"解档失败");
    } else {
       NSLog(@"解档成功--name = %@,age = %d",t2.name, t2.age);
    }
   
    
}



@end
